package creditsProject.client.manager;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

import creditsProject.dto.Credit;
import creditsProject.dto.Login;
import creditsProject.dto.RequestDto;
import creditsProject.dto.User;

public class ManagerGUI extends JFrame {
	private static Login login;
	private static User user;
	private static List<RequestDto> requests;
	private static String command;
	private static Credit credit;
	// private JPanel panel = new JPanel();
	private JTextField textFieldPhoneNumber = new JTextField(20);
	private JPasswordField textFieldPassword = new JPasswordField(8);
	private JButton button = new JButton("LOGIN");
	private JButton buttonBye = new JButton("BYE");
	private JLabel labelPhone = new JLabel("Phone number");
	private JLabel labelPassword = new JLabel("Password");
	private static JLabel label = new JLabel("  ");
	private static JLabel labelMenu = new JLabel("  ");
	private ActionListener myListener = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			try {
				login = new Login(Integer.parseInt(textFieldPhoneNumber
						.getText()), textFieldPassword.getText());

				if (login != null && login.getPass() != null) {
					setLogin(login);
					setCommand("LOGIN");
				} else {
					setLabel("Enter login and password");
				}

			} catch (NumberFormatException nfe) {
				setLabel("Phone should consist of numbers");
			}

		}
	};

	private ActionListener listenerBye = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			System.out.println("bye-bye");
			setCommand("BYE");
			dispose();

		}
	};

	public static String getCommand() {
		return command;
	}

	public static void setCommand(String command) {
		ManagerGUI.command = command;
	}

	public static Login getLogin() {
		return login;
	}

	public static void setLogin(Login login) {
		ManagerGUI.login = login;
	}

	public static JLabel getLabel() {
		return label;
	}

	public static void setLabel(String label) {
		ManagerGUI.label.setText(label);
	}

	public static Credit getCredit() {
		return credit;
	}

	public static void setCredit(Credit credit) {
		ManagerGUI.credit = credit;
	}
	
	public static JLabel getLabelMenu() {
		return labelMenu;
	}

	public static void setLabelMenu(String labelMenu) {
		ManagerGUI.labelMenu.setText(labelMenu);
	}

	public ManagerGUI() {
		setTitle("Manager");
		this.setSize(500, 250);
		this.setLocation(200, 200);
		Box panel = Box.createVerticalBox();
		this.add(panel);
		panel.add(labelPhone);
		labelPhone.setAlignmentX(CENTER_ALIGNMENT);

		panel.add(textFieldPhoneNumber);
		textFieldPhoneNumber.setHorizontalAlignment(JTextField.CENTER);
		textFieldPhoneNumber.setAlignmentX(CENTER_ALIGNMENT);

		panel.add(Box.createVerticalStrut(10));
		panel.add(labelPassword);
		labelPassword.setAlignmentX(CENTER_ALIGNMENT);

		panel.add(textFieldPassword);
		textFieldPassword.setHorizontalAlignment(JTextField.CENTER);
		textFieldPassword.setAlignmentX(CENTER_ALIGNMENT);

		panel.add(Box.createVerticalStrut(10));
		panel.add(button);
		button.setAlignmentX(CENTER_ALIGNMENT);

		panel.add(Box.createVerticalStrut(10));
		panel.add(buttonBye);
		buttonBye.setAlignmentX(CENTER_ALIGNMENT);

		panel.add(Box.createVerticalStrut(10));
		panel.add(label);
		label.setAlignmentX(CENTER_ALIGNMENT);
		panel.add(Box.createVerticalStrut(10));

		button.addActionListener(myListener);
		buttonBye.addActionListener(listenerBye);

	}

	private JButton buttonShowRequest = new JButton("Credits Requests");
	private JButton buttonAddUser = new JButton("Add new User");
	private JButton buttonAddCredit = new JButton("Add new credit");

	private ActionListener addUser = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			setLabel("");
			ManagerGUI mg1 = new ManagerGUI();
			mg1.ManagerAddUser();
			mg1.setVisible(true);

		}
	};
	private ActionListener addCred = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			setLabel("");
			ManagerGUI mg1 = new ManagerGUI();
			mg1.ManagerAddCredit();
			mg1.setVisible(true);

		}
	};
private JPanel panLable = new JPanel(); 
	public void ManagerMenu() {
		this.setSize(500, 250);
		this.setLocation(200, 200);
		Box panel = Box.createVerticalBox();
		this.add(panel);

		panel.add(Box.createVerticalStrut(10));
		panel.add(buttonShowRequest);
		buttonShowRequest.setAlignmentX(CENTER_ALIGNMENT);

		panel.add(Box.createVerticalStrut(10));
		panel.add(buttonAddUser);
		buttonAddUser.setAlignmentX(CENTER_ALIGNMENT);

		panel.add(Box.createVerticalStrut(10));
		panel.add(buttonAddCredit);
		buttonAddCredit.setAlignmentX(CENTER_ALIGNMENT);

		panel.add(Box.createVerticalStrut(10));
		panel.add(buttonBye);
		buttonBye.setAlignmentX(CENTER_ALIGNMENT);

		panel.add(Box.createVerticalStrut(20));
		panel.add(panLable);
		panLable.setAlignmentX(CENTER_ALIGNMENT);
		panLable.add(labelMenu);
		//label.setAlignmentX(CENTER_ALIGNMENT);
		panel.add(Box.createVerticalStrut(10));

		// buttonBye.addActionListener(listenerBye);
		buttonAddUser.addActionListener(addUser);
		buttonShowRequest.addActionListener(showRequests);
		buttonAddCredit.addActionListener(addCred);
	}

	private JLabel labelFIO = new JLabel("Enter user name");
	private JTextField FIOtextField = new JTextField();

	private JLabel labelDateOfBirth = new JLabel("Enter user's date of birth");
	private JTextField DateOfbirthtextField = new JTextField();

	private JLabel labelPhoneNumb = new JLabel("Enter user's phone");
	private JTextField PhonetextField = new JTextField(12);

	private JLabel labelAddress = new JLabel("Enter user's address");
	private JTextField AddresstextField = new JTextField();

	private JButton buttonCommitUser = new JButton("Add User");
	private JButton buttonBack = new JButton("Back");

	public static User getUser() {
		return user;
	}

	public static void setUser(User user) {
		ManagerGUI.user = user;
	}

	private ActionListener listenerCommitUser = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			try {
				User user1 = new User(0, FIOtextField.getText(),
						DateOfbirthtextField.getText(),
						AddresstextField.getText(),
						Integer.parseInt(PhonetextField.getText()), "", "");

				if (user1 != null) {
					setUser(user1);
					setCommand("ADDUSER");
					setLabel("User " + user1.getFio() + " created");
					dispose();
				}
			} catch (NumberFormatException NFE) {
				setLabel("ENTER RIGHT DATA");
			}
		}
	};

	public void ManagerAddUser() {
		this.setSize(500, 250);
		this.setLocation(700, 200);
		Box addUsers = Box.createVerticalBox();
		this.add(addUsers);
		addUsers.add(labelFIO);
		labelFIO.setAlignmentX(CENTER_ALIGNMENT);

		addUsers.add(FIOtextField);
		FIOtextField.setHorizontalAlignment(JTextField.CENTER);
		FIOtextField.setAlignmentX(CENTER_ALIGNMENT);

		addUsers.add(labelDateOfBirth);
		labelDateOfBirth.setAlignmentX(CENTER_ALIGNMENT);

		addUsers.add(DateOfbirthtextField);
		DateOfbirthtextField.setHorizontalAlignment(JTextField.CENTER);
		DateOfbirthtextField.setAlignmentX(CENTER_ALIGNMENT);

		addUsers.add(labelPhoneNumb);
		labelPhoneNumb.setAlignmentX(CENTER_ALIGNMENT);

		addUsers.add(PhonetextField);
		PhonetextField.setHorizontalAlignment(JTextField.CENTER);
		PhonetextField.setAlignmentX(CENTER_ALIGNMENT);

		addUsers.add(labelAddress);
		labelAddress.setAlignmentX(CENTER_ALIGNMENT);

		addUsers.add(AddresstextField);
		AddresstextField.setHorizontalAlignment(JTextField.CENTER);
		AddresstextField.setAlignmentX(CENTER_ALIGNMENT);

		addUsers.add(Box.createVerticalStrut(10));
		addUsers.add(buttonCommitUser);
		buttonCommitUser.setAlignmentX(CENTER_ALIGNMENT);
		addUsers.add(label);
		label.setAlignmentX(CENTER_ALIGNMENT);
		addUsers.add(Box.createVerticalStrut(10));

		buttonCommitUser.addActionListener(listenerCommitUser);

	}

	private ActionListener showRequests = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			setCommand("GETREQUESTS");

		}
	};

	public static List<RequestDto> getRequests() {
		return requests;
	}

	public static void setRequests(List<RequestDto> requests) {
		ManagerGUI.requests = requests;
	}

	private JButton approveButton = new JButton("Approve");
	private JButton declineButton = new JButton("Decline");

	private static List<Integer> idRequests = new ArrayList<>();

	public static List<Integer> getIdRequests() {
		return idRequests;
	}

	public static void setIdRequests(List<Integer> idRequests) {
		ManagerGUI.idRequests = idRequests;
	}

	public static void clearIdRequests() {
		ManagerGUI.idRequests.clear();
	}

	private static List<Integer> userPhonesList = new ArrayList<>();

	public static List<Integer> getUserPhones() {
		return userPhonesList;
	}

	public static void setUserPhones(List<Integer> userPhones) {
		ManagerGUI.userPhonesList = userPhones;
	}

	public static void clearUserPhones() {
		ManagerGUI.userPhonesList.clear();
	}

	private HashSet<Integer> reqId = new HashSet<>();
	private HashSet<Integer> userPhonesHash = new HashSet<>();

	JPanel panelButton = new JPanel();
	
	public void ShowRequest() {

		this.setSize(500, 250);
		this.setLocation(700, 200);
		Box requestsPanel = Box.createVerticalBox();
		this.add(requestsPanel);

		DefaultTableModel model = new DefaultTableModel(null, new String[] {
				"Check", "Id", "User", "Phone", "Credit name" }) {
			public Class getColumnClass(int c) {
				switch (c) {
				case 0:
					return Boolean.class;
				default:
					return String.class;
				}
			}
		};

		int phone = 0;
		String creditName = "";
		String name = "";
		int requestId = 0;
		Vector columnData = new Vector<>();
		Vector vecData = new Vector<>();
		JCheckBox chkBox = new JCheckBox();
		for (int i = 0; i < requests.size(); i++) {
			columnData = new Vector<>();
			requestId = requests.get(i).getRequestId();
			phone = requests.get(i).getPhoneNumber();
			name = requests.get(i).getUserName();
			creditName = requests.get(i).getCreditName();
			columnData.add(Boolean.FALSE);
			columnData.add(new Integer(requestId));
			columnData.add(new String(name));
			columnData.add(new Integer(phone));
			columnData.add(new String(creditName));
			model.addRow(columnData);
		}

		JTable tableRequests = new JTable(model);
		tableRequests.getModel().addTableModelListener(
				new TableModelListener() {

					@Override
					public void tableChanged(TableModelEvent e1) {

						int row = e1.getFirstRow();
						int column = e1.getColumn();
						DefaultTableModel model = (DefaultTableModel) e1
								.getSource();
						String columnName = model.getColumnName(column);
						Boolean data = (Boolean) model.getValueAt(row, column);
						if (data == true) {
							Integer id = (Integer) model.getValueAt(row,
									column + 1);
							reqId.add(id);

							Integer usrPh = (Integer) model.getValueAt(row,
									column + 3);
							userPhonesHash.add(usrPh);
						} else {
							Integer id = (Integer) model.getValueAt(row,
									column + 1);
							reqId.remove(id);

							Integer usrPh = (Integer) model.getValueAt(row,
									column + 3);
							userPhonesHash.remove(usrPh);
						}
					}
				});
		requestsPanel.add(new JScrollPane(tableRequests), BorderLayout.CENTER);
		requestsPanel.validate();

		requestsPanel.add(Box.createVerticalStrut(10));
		requestsPanel.add(panelButton);
		panelButton.setAlignmentX(CENTER_ALIGNMENT);
		panelButton.add(approveButton);

		// approveButton.setAlignmentX(CENTER_ALIGNMENT);
		approveButton.addActionListener(approveListener);

		panelButton.add(declineButton);
		// declineButton.setAlignmentX(CENTER_ALIGNMENT);
		declineButton.addActionListener(declineListener);

		panelButton.add(showUserHistoryButton);
		// declineButton.setAlignmentX(CENTER_ALIGNMENT);
		showUserHistoryButton.addActionListener(showUserHistoryListener);

		requestsPanel.add(Box.createVerticalStrut(10));
		requestsPanel.add(label);

	}

	private JButton showUserHistoryButton = new JButton(
			"Show user credit history");
	private ActionListener showUserHistoryListener = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			userPhonesList.addAll(userPhonesHash);
			dispose();
			setCommand("GETUSERHISTORY");

		}
	};

	private ActionListener approveListener = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent arg0) {
			idRequests.clear();
			idRequests.addAll(reqId);
			setCommand("APROVEREQUEST");
			dispose();
		}
	};

	private ActionListener declineListener = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent arg0) {
			idRequests.clear();
			idRequests.addAll(reqId);
			setCommand("DECLINEREQUEST");
			dispose();
		}
	};

	public void ShowHistory() {

		this.setSize(600, 250);
		this.setLocation(700, 200);
		Box historyPanel = Box.createVerticalBox();
		this.add(historyPanel);

		DefaultTableModel model = new DefaultTableModel(null, new String[] {
				"Date", "Request id", "Credit Name", "Approved", "Declined" }) {
			public Class getColumnClass(int c) {
				switch (c) {
				case 4:
					return Boolean.class;
				case 3:
					return Boolean.class;
				default:
					return String.class;
				}
			}

			public boolean isCellEditable(int row, int column) {
				return false;
			}

		};

		String date = "";
		int requestId = 0;
		String name = "";

		Vector columnData = new Vector<>();
		Vector vecData = new Vector<>();
		JCheckBox chkBox = new JCheckBox();
		for (int i = 0; i < requests.size(); i++) {
			columnData = new Vector<>();
			columnData.add(new String(requests.get(i).getDate()));
			columnData.add(new Integer(requests.get(i).getRequestId()));
			columnData.add(new String(requests.get(i).getCreditName()));
			columnData.add(new Boolean(requests.get(i).isApproved()));
			columnData.add(new Boolean(requests.get(i).isDeclined()));
			model.addRow(columnData);
		}

		JTable tableCredits = new JTable(model);

		historyPanel.add(new JScrollPane(tableCredits), BorderLayout.CENTER);
		historyPanel.validate();

		historyPanel.add(Box.createVerticalStrut(10));
		historyPanel.add(label);

	}

	

	private JLabel labelCreditName = new JLabel("Enter credit name");
	private JLabel labelDescription = new JLabel("Enter credit description");
	private JLabel labelDuration = new JLabel("Enter credit duration");

	private JTextField creditNamatextField = new JTextField();
	private JTextField descriptiontextField = new JTextField();
	private JTextField durationtextField = new JTextField();

	private JButton buttonCommitCredit = new JButton("Create credit");

	private ActionListener commitCreditListener = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			try {
				Credit credit = new Credit(0, creditNamatextField.getText(),
						descriptiontextField.getText(),
						durationtextField.getText());
				if (credit != null && !credit.getName().equals("")) {
					setCredit(credit);
					setCommand("ADDCREDIT");
					setLabelMenu("Credit " + credit.getName() + " created");
					dispose();
				} else{
					setLabel("Credit name have to be not empty");
				}
			} catch (NumberFormatException NFE) {
				setLabel("ENTER RIGHT DATA");
			}
		}

	};

	public void ManagerAddCredit() {
		this.setSize(500, 250);
		this.setLocation(700, 200);
		Box addCredit = Box.createVerticalBox();
		this.add(addCredit);
		addCredit.add(labelCreditName);
		labelCreditName.setAlignmentX(CENTER_ALIGNMENT);

		addCredit.add(creditNamatextField);
		creditNamatextField.setHorizontalAlignment(JTextField.CENTER);
		creditNamatextField.setAlignmentX(CENTER_ALIGNMENT);

		addCredit.add(labelDescription);
		labelDescription.setAlignmentX(CENTER_ALIGNMENT);

		addCredit.add(descriptiontextField);
		descriptiontextField.setHorizontalAlignment(JTextField.CENTER);
		descriptiontextField.setAlignmentX(CENTER_ALIGNMENT);

		addCredit.add(labelDuration);
		labelDuration.setAlignmentX(CENTER_ALIGNMENT);

		addCredit.add(durationtextField);
		durationtextField.setHorizontalAlignment(JTextField.CENTER);
		durationtextField.setAlignmentX(CENTER_ALIGNMENT);

		addCredit.add(Box.createVerticalStrut(10));
		addCredit.add(buttonCommitCredit);
		buttonCommitCredit.setAlignmentX(CENTER_ALIGNMENT);
		
		buttonCommitCredit.addActionListener(commitCreditListener);
		
		addCredit.add(label);
		label.setAlignmentX(CENTER_ALIGNMENT);
		addCredit.add(Box.createVerticalStrut(10));

		

	}
}
